<template>
  <div>
    <script :id="id" type="text/plain" ref="editorId"></script>
  </div>
</template>
<script>
export default {
  name: 'UE',
  data() {
    return {
      editor: null,
    }
  },
  props: {
    config: {
      type: Object,
    },
    id: {
      type: String,
    },
    content: {
      type: String,
    },
    value: {
      type: String,
      default: null,
    },
  },
  mounted() {
    this._initEditor()
  },
  watch: {
    value: function (val) {
      this.value = val
      this._initEditor()
      this.editor.setContent(val)
    },
  },

  methods: {
    resetContent() {
      this.editor.setContent('')
    },

    _initEditor() {
      // 初始化
      this.$nextTick(function f1() {
        // 保证 this.$el 已经插入文档
        this.$refs.editorId.id = this.id //创建动态id
        this.editor = UE.getEditor(this.id, this.config)
        this.editor.ready(
          function f2() {
            this.editor.setContent(this.value)
            this.editor.addListener(
              'contentChange',
              function () {
                const wordCount = this.editor.getContentLength(true)
                const content = this.editor.getContent()
                const plainTxt = this.editor.getPlainTxt()
                const htmlCont = this.editor.getAllHtml()
                // 编辑器内容有变动,通知父组件
                this.$emit('input', {
                  wordCount: wordCount,
                  content: content,
                  plainTxt: plainTxt,
                  htmlCont: htmlCont,
                })
              }.bind(this)
            )
            // editor初始化后操作
            this.$emit('ready', this.editor)
          }.bind(this)
        )
      })
    },
    getUEContent() {
      // 获取含标签内容方法
      return this.editor.getContent()
    },
    setFocus() {
      return this.editor.focus()
    },
    setContexts(item) {
      this.editor.execCommand('inserthtml', item)
      this.editor.execCommand('forecolor', '#333')
    },
  },
  destroyed() {
    this.editor.destroy()
  },
}
</script>
